<template>
	<view class="flex">
		<template v-if="longPress == '2'">
			<view class="mr10">
				<text class="text-red">松手停止</text>
				<text>，{{'剩余：' + count + 's'}}</text>
			</view>
		</template>
		<view :class="['btn-recorder','flex',longPress == '1'?'':'active']"  @longpress="longpressBtn" @touchend="touchendBtn">
			<u-icon name="mic" size="18" :color="longPress == '1'?'#999999':'#ffffff'"></u-icon>
			{{longPress == '1' ? '按住说话' : '说话中...'}}
		</view>
	</view>
</template>

<script>
	import {
		upload
	} from '@/common/api.js';
	
	const recorderManager = uni.getRecorderManager();
	const innerAudioContext = uni.createInnerAudioContext();
	let init; // 录制时长计时器
	let timer; // 播放 录制倒计时
	let uploadTimer; // 上传文件计时器

	export default {
		name: "recorder-btn",
		props: {
			name:{
				type:String,
				default:'0'
			}
		},
		data() {
			return {
				uploadTime:0,//上传时长
				btnText: '按住 说话',
				btnLoading: false,
				count: null, // 录制倒计时
				longPress: '1', // 1显示 按住说话 2显示 说话中
				delShow: false, // 删除提示框显示隐藏
				time: 0, //录音时长
				duration: 60000, //录音最大值ms 60000/1分钟
				tempFilePath: '', //音频路径
				playStatus: 0, //录音播放状态 0:未播放 1:正在播放
				_upError:'',
				result:''
			};
		},
		watch:{

		},
		computed:{
		},
		methods: {
			upload(){
				let _this = this;
				// let tempFilePath = '/static/test_voice_sc_mp3_16_mono.mp3';
				let tempFilePath = this.tempFilePath;
				uni.showLoading({
					title: '加载中'
				});
				_this.recordingUploadTimer();
				uni.uploadFile({
					url: 'https://ai.fmn315.cn/upload_sale/',
					filePath: tempFilePath,
					name: 'file',
					formData: {},
					success: (uploadFileRes) => {
						// console.log(uploadFileRes);
						// console.log(result['食材名称']);
						try{
							let result = JSON.parse(JSON.parse(uploadFileRes.data));
							_this.result = result['数量'];
							
							_this.$emit('out',_this.result,_this.name);
							
							uni.hideLoading();
						}catch(e){
							//TODO handle the exception
							uni.$u.toast('翻译失败');
						}
					},
					fail:(res)=>{
						// console.log('[https://ai.fmn315.cn/upload_sale]uploadFile-fail');
						console.log(res);
						// _upError
						// this._upError = JSON.stringify(res);
						uni.$u.toast('上传失败');
					},
					complete:()=>{
						_this.recordingUploadTimer(1);
					}
				});
			},
			longpressBtn() {
				console.log('longpress');
			},
			touchendBtn() {

			},
			// 倒计时
			countdown(val) {
				let _then = this;
				if(!val){
					clearInterval(timer);
				}
				_then.count = Number(val);
				timer = setInterval(function() {
					if (_then.count > 0) {
						_then.count--
					} else {
						_then.longPress = '1';
						clearInterval(timer);
					}
				}, 1000);
			},
			// 长按录音事件
			longpressBtn() {
				this.longPress = '2';
				this.countdown(60); // 倒计时
				clearInterval(init) // 清除定时器
				// return;
				recorderManager.onStop((res) => {
					console.log('录音停止recorderManager.onStop1');
					this.tempFilePath = res.tempFilePath;
					this.recordingTimer(this.time);
					this.countdown(); // 清除倒计时
				})
				const options = {
					duration: this.duration, // 指定录音的时长，单位 ms
					sampleRate: 16000, // 采样率
					numberOfChannels: 1, // 录音通道数
					encodeBitRate: 96000, // 编码码率
					format: 'mp3', // 音频格式，有效值 aac/mp3
					frameSize: 10, // 指定帧大小，单位 KB
				}
				this.recordingTimer();
				recorderManager.start(options);
				// 监听音频开始事件
				recorderManager.onStart((res) => {
					// console.log('recorderManager.onStart');
					// console.log(res)
				})
			},
			// 长按松开录音事件
			touchendBtn() {
				this.longPress = '1';
				// return;
				recorderManager.onStop((res) => {
					console.log('录音停止recorderManager.onStop2');
					// console.log(res);
					this.tempFilePath = res.tempFilePath;
					this.upload();
				})
				this.recordingTimer(this.time);
				this.countdown(); // 清除倒计时
				recorderManager.stop()
			},
			recordingTimer(time) {
				let that = this;
				if (time == undefined) {
					// 将计时器赋值给init
					init = setInterval(function() {
						that.time++
					}, 1000);
				} else {
					clearInterval(init)
				}
			},
			recordingUploadTimer(time) {
				let that = this;
				if (time == undefined) {
					// 将计时器赋值给uploadTimer
					that.uploadTime = 0;
					uploadTimer = setInterval(function() {
						that.uploadTime++
					}, 1);
				} else {
					console.log('上传文件毫秒数：'+that.uploadTime);
					clearInterval(uploadTimer)
				}
			},
			// 删除录音
			delBtn() {
				this.delShow = false;
				this.time = 0
				this.tempFilePath = ''
				this.playStatus = 0
				innerAudioContext.stop()
			},
			// 播放
			playBtn() {
				innerAudioContext.src = this.tempFilePath
				//在ios下静音时播放没有声音，默认为true，改为false就好了。
				// innerAudioContext.obeyMuteSwitch = false
				//点击播放
				if (this.playStatus == 0) {
					this.playStatus = 1;
					innerAudioContext.play();
					this.countdown(this.time); // 倒计时
				} else {
					this.playStatus = 0;
					innerAudioContext.pause()
				}
				// //播放结束
				innerAudioContext.onEnded(() => {
					this.playStatus = 0;
					innerAudioContext.stop();
				})
			},
		}
	}
</script>

<style>
	.btn-recorder {
		border-radius: 60upx;
		line-height: 60upx;
		color: #333333;
		background-color: #ffffff;
		border-color: #999999;
		border-width: 1px;
		border-style: solid;
		text-align: center;
		padding:0 20upx ;
	}
	.btn-recorder.active{
		color: #fff;
		background-color: #5ac725;
		border-color: #5ac725;
	}
</style>